<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\BaseController;
use app\index\model\GoodsProp;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use think\facade\View;
use think\Image;

class Brand extends BaseController
{

    public function brand()
    {

        //$data=Request::get('','','');
        $brand_name=Request::get('brand_name','','trim,htmlspecialchars,strip_tags');
        $if_show=Request::get('if_show','2','trim,htmlspecialchars,strip_tags');
        $brand_logo=Request::get('brand_logo',[],'trim,htmlspecialchars,strip_tags');
        $get=Request::get();
        $data=[
            'brand_name'=>$brand_name,
            'if_show'=>$if_show,
            'brand_logo'=>$brand_logo,
        ];


        $arr=\app\index\model\Brand::getBrand($data,$data);

        $list=\app\index\model\Brand::getBrand($data,$get);



        View::assign('list',$list);
        View::assign($get);
        $empty="<tr><td colspan='8'>暂无数据</td></tr>";
        View::assign('empty',$empty);
        View::assign('data',$data);
        return View::fetch('',['arr'=>$arr]);



    }
    protected function moveTempFile($oldfile,$newfile,$prefix='storage/'){
        try{
            $arr=explode('/',$newfile);
            unset($arr[count($arr)-1]);
            $dir = implode('/',$arr);
            //$dir=$prefix.$dir;
            if (!is_dir($prefix.$dir)){
                mkdir($prefix.$dir,777,true);
            }


            copy($prefix.$oldfile,$prefix.$newfile);
            Image::open('storage/'.$newfile)->thumb(300,150,image::THUMB_FIXED)->save('storage/'.$newfile);
            if (!is_dir($prefix.'new/'.$dir)){
                mkdir($prefix.'new/'.$dir,777,true);

                $font = PROJECT_ROOT_PATH.'/public/font/simfang.ttf';
                Image::open($prefix.$oldfile)
                    ->text($prefix.$oldfile,$font,50,'#FF0000')
                    ->save($prefix.'new/'.$newfile);
            }

           return unlink($prefix.$oldfile) ;

        }catch (\Exception $e){
            return false;
        }

    }

    public function add_brand()
    {


        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');
            if ($_FILES['brand_logo']['error']!=4){
                $brand_logo=Request::file('brand_logo','');
            }else{
                $this->error('没有文件上传');
            }



            try {
                $logo=['brand_logo'=>$brand_logo];
                validate(\app\validate\Brand::class)->scene('logo')->check($logo);
                validate(\app\validate\Brand::class)->check($post);
                $savename = \think\facade\Filesystem::disk('public')->putFile('up',$brand_logo,'get_uploadfile_name');
                $savename = str_replace('\\','/',$savename);
                list($begin_dir,$filename)=explode('/',$savename,2);
                $newname = 'data/upload/'.$filename;

                $post['brand_logo']=$newname;

            } catch (\think\exception\ValidateException $e) {
                // 验证失败 输出错误信息
                $this->error($e->getMessage());

            }catch (\Exception $e){}






            $jumpPath='';
            if('1'==$post['button'])   $jumpPath = url('brand');
            if ('2'==$post['button'])  $jumpPath = url('add_brand');
            $brandObj = new \app\index\model\Brand();
            $result = $brandObj->add($brandObj,$post);





            if($result ){
                $this->moveTempFile($savename,$newname);


                $this->success("成功！".$brandObj->getInsertId(),$jumpPath,[],20) ;


            }else{
                $this->error("失败！原因：".$brandObj->getError()) ;
            }
        }else{
            return View::fetch();
        }
    }
    //修改

    public function edit_brand(){
        $param=Request::param('param',[],'trim,htmlspecialchars,strip_tags');




        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');
            $brand_logo_old=Request::post('brand_logo_old','','');
            if ($_FILES['brand_logo']['error']!=4){
                $brand_logo=Request::file('brand_logo','');
            }else{
                $this->error('没有文件上传');
            }

            try {

                //$post['brand_logo']=$brand_logo;


                validate(\app\validate\Brand::class)->scene('logo')->check(['brand_logo'=>$brand_logo]);
                validate(\app\validate\Brand::class)->scene('edit')->check($post);


                // 验证通过 执行上传
                $savename = \think\facade\Filesystem::disk('public')->putFile('data/upload/', $brand_logo, 'get_uploadfile_name');

                $post['brand_logo'] = str_replace('\\', '/', $savename);


            } catch (\think\exception\ValidateException $e) {
                // 验证失败 输出错误信息
               $this->error($e->getMessage());


            }catch (\Exception $e){}



            if (isset($brand_logo_old)&& is_file($brand_logo_old)){
                $arr=explode('/',$brand_logo_old);
                unset($arr[count($arr)-1]);
                $dir = implode('/',$arr);
                if (  is_dir('storage/'.$dir)){
                    unlink('storage/'.$brand_logo_old);
                }
            }




            $brandObj = new \app\index\model\Brand();

            $result = $brandObj->edit($post);




            if($result){

                    Image::open('storage/'.$post['brand_logo'])
                        ->thumb(300,150,image::THUMB_FIXED)
                        ->save('storage/'.$post['brand_logo']);



                $this->success('修改成功！',url('brand',$param),[],20);
            }else{
                $this->error('修改失败！');
            }


        }else{
            // 显示修改的页面
            $id = Request::get('id','','trim,htmlspecialchars,strip_tags');


            $brandObj = \app\index\model\Brand::find($id);
            if(empty($brandObj)){
                $this->error('参数错误！');
            }

            return View::fetch('',$brandObj->toArray());
        }

    }

    public function del(){
        $id =Request::get('id','','');
        //利用id去查商品表
        //$pin=\app\index\model\Goods::getGoods()->where('brand',$id)->count();
       $pin= Db::table('ecm_goods')->field('goods_id')->where('brand',$id)->find();

       $image=Db::table('ecm_brand')->getFieldByBrandId($id,'brand_logo');

        Db::startTrans();
        if (empty($pin)){
            try{
                \app\index\model\Brand::destroy($id);
                //删除图片
                $arr=explode('/','storage/'.$image);

                unset($arr[count($arr)-1]);
                $dir = implode('/',$arr);

                if (isset($image) && is_dir($dir)){
                    unlink('storage/'.$image);
                    rmdir($dir);
                }
                //提交事务
                Db::commit();

            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('删除成功!',getenv("HTTP_REFERER"));

        }else{
            // 回滚事务
            Db::rollback();
            $this->error('删除失败，商品已被占用！');
            return View::fetch();
        }


    }
    //多删
    public function all_del(){
        $id =Request::get('id','','');
        $pin= Db::table('ecm_goods')->field('goods_id')->whereIn('brand',$id)->count();
        $image=Db::table('ecm_brand')->field('brand_logo')->whereIn('brand_id',$id)->select()->toArray();

        //利用id去查商品表
        if (empty($pin)){
            \app\index\model\Brand::destroy($id);
            foreach ($image as $v ) {

                $arr = explode('/','storage/' . $v['brand_logo']) ;
                unset($arr[count($arr) - 1]);
                $dir = implode('/', $arr);
                if (isset($v['brand_logo']) && is_dir($dir)) {
                    unlink('storage/' . $v['brand_logo']);
                    rmdir($dir);
                }
            }
            $this->success('删除成功!',getenv("HTTP_REFERER"));
        }else{
            $this->error('删除失败，商品已被占用！');
        }



    }







    //
}
